package com.ybg.share.schedule;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybg.framework.core.NetasetSendEmail;
import com.ybg.share.core.dbapi.entity.ShareReceiveEmail;
import com.ybg.share.core.dbapi.entity.ShareStock;
import com.ybg.share.core.dbapi.entity.ShareStockDayK;
import com.ybg.share.core.dbapi.entity.ShareStockGravity;
import com.ybg.share.core.dbapi.service.ShareReceiveEmailService;
import com.ybg.share.core.dbapi.service.ShareStockDayKService;
import com.ybg.share.core.dbapi.service.ShareStockGravityService;
import com.ybg.share.core.dbapi.service.ShareStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ShareStockGravityTask {
    @Autowired
    private ShareStockService shareStockService;
    @Autowired
    private ShareStockDayKService shareStockDayKService;
    @Autowired
    private ShareStockGravityService shareStockGravityService;
    @Autowired
    private ShareReceiveEmailService shareReceiveEmailService;
    @Autowired
    private NetasetSendEmail netasetSendEmail;
    @Scheduled(cron = "0 30 5 * * ?")
    public void runTask() {
        log.info("地心引力线Task start");
        QueryWrapper<ShareStock> shareStockWrapper = new QueryWrapper<>();
        shareStockWrapper.eq(ShareStock.STATUS, true);
        List<ShareStock> list = shareStockService.list(shareStockWrapper);
        for (ShareStock shareStock : list) {
            QueryWrapper<ShareStockDayK> dayKWrapper = new QueryWrapper<>();
            dayKWrapper.eq(ShareStockDayK.STOCK_ID, shareStock.getId());
            dayKWrapper.orderByDesc(ShareStockDayK.REF_DATE);
            dayKWrapper.last(" limit 72 ");
            List<ShareStockDayK> dayKList = shareStockDayKService.list(dayKWrapper);
            if (dayKList == null || dayKList.size() < 72) {
                continue;
            }
            //求三十日均线和72日均线的和除以2
            Double avg72 = dayKList.stream().collect(Collectors.averagingDouble(x -> x.getClosePrice().doubleValue()));
            Double avg30 = dayKList.subList(0, 30).stream().collect(Collectors.averagingDouble(x -> x.getClosePrice().doubleValue()));
            // 倒序列表
            BigDecimal closePrice = dayKList.get(0).getClosePrice();
            Double gravityValue = (avg72 + avg30) / 2;
            log.info(gravityValue.toString());
            BigDecimal result = new BigDecimal(gravityValue.toString()).setScale(3, RoundingMode.UP);
            ShareStockGravity shareStockGravity = new ShareStockGravity();
            //  shareStockGravity.setId(0L);
            shareStockGravity.setStockId(shareStock.getId());
            shareStockGravity.setStockName(shareStock.getName());
            shareStockGravity.setStockCode(shareStock.getCode());
            shareStockGravity.setNowPrice(closePrice);
            shareStockGravity.setLinePrice(result);
            shareStockGravity.setLinePrice120(result.multiply(new BigDecimal("1.2")).setScale(3, RoundingMode.UP));
            shareStockGravity.setLinePrice110(result.multiply(new BigDecimal("1.1")).setScale(3, RoundingMode.UP));
            shareStockGravity.setLinePrice90(result.multiply(new BigDecimal("0.9")).setScale(3, RoundingMode.UP));
            shareStockGravity.setLinePrice80(result.multiply(new BigDecimal("0.8")).setScale(3, RoundingMode.UP));
            shareStockGravity.setUpdateTime(LocalDateTime.now());
            shareStockGravity.setDescription(resultDescription(closePrice, result));
            if(closePrice.compareTo(BigDecimal.ZERO)==0){
                shareStockGravity.setRate(BigDecimal.ZERO);
            }else{
                shareStockGravity.setRate(closePrice.divide(result,3).setScale(3, RoundingMode.UP));
            }

            QueryWrapper<ShareStockGravity> tWrapper = new QueryWrapper();
            tWrapper.eq(ShareStockGravity.STOCK_ID, shareStock.getId());
            ShareStockGravity stockGravity = shareStockGravityService.getOne(tWrapper);
            if (stockGravity == null) {
                shareStockGravityService.save(shareStockGravity);
            } else {
                shareStockGravity.setId(stockGravity.getId());
                shareStockGravityService.updateById(shareStockGravity);
            }

            //大盘检测 发生email

        }

        QueryWrapper<ShareReceiveEmail> emailWrapper = new QueryWrapper<>();
        emailWrapper.le(ShareReceiveEmail.START_TIME, DateUtil.now());
        emailWrapper.ge(ShareReceiveEmail.END_TIME, DateUtil.now());
        List<ShareReceiveEmail> emailList = shareReceiveEmailService.list(emailWrapper);
        String contents=sendEmailToUser();
        for (ShareReceiveEmail shareReceiveEmail : emailList) {
            try {
                netasetSendEmail.sendMail(shareReceiveEmail.getEmail(), "ybg_share智能推荐股票", contents);
            }catch (Exception e){
                log.error("任务异常{}", e);
                break;
            }

        }
        log.info("地心引力线Task end");
    }

    private String sendEmailToUser() {

        QueryWrapper<ShareStockGravity> gravityWrapper = new QueryWrapper<>();
        gravityWrapper.apply(ShareStockGravity.NOW_PRICE + "<" + ShareStockGravity.LINE_PRICE);
        //排序 避免查看混乱
        gravityWrapper.orderByDesc(ShareStockGravity.DESCRIPTION);
        List<ShareStockGravity> shareStockGravities = shareStockGravityService.list(gravityWrapper);
        StringBuilder buffer = new StringBuilder();
        buffer.append("<html><head>");
        buffer.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
        buffer.append("<base target=\"_blank\" />");
        buffer.append("</head>");
        buffer.append("<body>");
        buffer.append("<a href=\"http://www.88ybg.com:8090/ybg_share/ureport/preview?_u=mysql:stockList.ureport.xml\">点我 点我 点我！！！！！</a>");


        buffer.append("</body>");
        buffer.append("</html>");
        return buffer.toString();

    }


    private String resultDescription(BigDecimal nowPrice, BigDecimal gravityValue) {
        if (nowPrice.compareTo(gravityValue.multiply(new BigDecimal("1.2"))) > 0) {
            return "股价处于高位，建议减仓";
        }
        if (nowPrice.compareTo(gravityValue.multiply(new BigDecimal("1.1"))) > 0) {
            return "股价快见顶，建议关注 准备减仓";
        }
        if (nowPrice.compareTo(gravityValue.multiply(new BigDecimal("1.0"))) > 0) {
            return "股价不上不下，观望为主";
        }
        if (nowPrice.compareTo(gravityValue.multiply(new BigDecimal("0.9"))) > 0) {
            return "股价可以适当买入不建议全仓";
        }
        if (nowPrice.compareTo(gravityValue.multiply(new BigDecimal("0.8"))) > 0) {
            return "买入信号比较强烈，股价较低,考虑加仓";
        }
        if (nowPrice.compareTo(gravityValue.multiply(new BigDecimal("0.8"))) <= 0) {
            return "特强买入信号，可以全仓，但要关注股票基本面";
        }

        return "无法判断";
    }



}
